/**
 *Copyright (c) 2024 watereyes
 * workflow is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.workflow.api.rule;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import org.koron.ebs.mybatis.SessionFactory;

import com.koron.workflow.api.rule.FilterRuleStrategy;
import com.koron.workflow.baseConfig.bean.DepartmentBean;
import com.koron.workflow.baseConfig.mapper.DepartmentMapper;
import com.koron.workflow.common.bean.StaffBean;

/**
 * 只选择本部门及子部门审核人
 * @author bin
 *
 */
public class FilterRuleStrategy1 implements FilterRuleStrategy{

	@Override
	public List<StaffBean> filter(SessionFactory factory, List<StaffBean> staffs, StaffBean initiator, int autoPicker) {
		DepartmentBean department = factory.getMapper(DepartmentMapper.class).queryForObject(initiator.getDepartmentid());
		List<DepartmentBean> departments = getChildren(factory, department, new ArrayList<DepartmentBean>());
		List<String> dIds = departments.stream().map(t -> t.getId()).collect(Collectors.toList());
		staffs = staffs.stream().filter(t -> t != null).filter(t -> dIds.contains(t.getDepartmentid())).collect(Collectors.toList());
		// 假如自动选人规则为：发起人
		if(autoPicker == 1 && staffs.contains(initiator)) {
			return Arrays.asList(initiator);
		}
		// 假如自动选人规则为：直属上司
		if(autoPicker == 2) {
			//TODO 待定
		}
		return staffs;
	}
	
	private List<DepartmentBean> getChildren(SessionFactory session, DepartmentBean sysDept, List<DepartmentBean> sysDepts){
		if(sysDept != null && sysDept.getParentCode() != null && !Objects.equals(sysDept.getCode(), sysDept.getParentCode())) {
			List<DepartmentBean> parents = session.getMapper(DepartmentMapper.class).queryForList(sysDept.getId(), null, null);
			for(DepartmentBean p : parents) {
				getChildren(session, p, sysDepts);
			}
		}
		if(sysDept != null) {
			sysDepts.add(sysDept);
		}
		return sysDepts;
	}
}
